#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <string.h>
#include <dlfcn.h>
#include "ca_module.h"

ca_module_t *ca_module_get(void)
{
  char path[255];
  char realpath[255];
  int  ret;
  char *p;
  void *dlhandler;
  ca_module_t *module;

  pid_t id = getpid();
  ret = snprintf(path, sizeof(path), "/proc/%d/exe", id);
  if (ret >= (int)sizeof(path))
    return NULL;

  ret = readlink(path, realpath, sizeof(realpath));
  if (ret < 0)
  {
    printf("readlink for %s failed, errno:%d error:%s\n", path, errno, strerror(errno));
    return NULL;
  }
  realpath[ret] = '\0';
printf("%s realpath=%s ret=%d\n", __func__, realpath, ret);
  p = strrchr(realpath, '/');
  p[1] = 0;
  strncat(realpath, "libcas.so", sizeof(realpath) - strlen(realpath));

  dlhandler = dlopen(realpath, RTLD_NOW);
  if (!dlhandler)
  {
    printf("dlopen %s failed, errno:%d error:%s\n", realpath, errno, strerror(errno));
	return NULL;
  }

  module = dlsym(dlhandler, "this_ca_module");
  if (!module)
  {
    printf("dlsym failed, errno:%d error:%s\n", errno, strerror(errno));
    dlclose(dlhandler);
    return NULL;
  }

  return module;
}

